package com.atguigu.gulimall.product.service.impl;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.AttrGroupDao;
import com.atguigu.gulimall.product.entity.AttrGroupEntity;
import com.atguigu.gulimall.product.service.AttrGroupService;


@Service("attrGroupService")
public class AttrGroupServiceImpl extends ServiceImpl<AttrGroupDao, AttrGroupEntity> implements AttrGroupService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrGroupEntity> page = this.page(
                new Query<AttrGroupEntity>().getPage(params),
                new QueryWrapper<AttrGroupEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params, Long catId) {
            // 如果三级分类的id为catId=0，则查询所有分类
        if (catId == 0) {
            // 构建Ipage对象，需要指定分页参数和查询参数
            IPage<AttrGroupEntity> iPage = this.page(new Query<AttrGroupEntity>().getPage(params), new QueryWrapper<AttrGroupEntity>());
            return new PageUtils(iPage);
        } else {
            // 存在catId，则进行条件查询
//          select * from pms_attr_group where cat_id = ? and (attr_group_name like %key% or attr_group_id=key)
            String key = (String)params.get("key");
            IPage<AttrGroupEntity> page = this.page(
                    new Query<AttrGroupEntity>().getPage(params),
                    new QueryWrapper<AttrGroupEntity>()
                        .eq("attr_group_id", catId)
                        .like(StringUtils.isNotBlank(key),"attr_group_name", key)
                        .or()
                        .eq(StringUtils.isNotBlank(key),"attr_group_id", key)
            );
            return new PageUtils(page);
        }
    }
}